/**
 * 
 */
package edu.arizona.bio5.onto.decomposition;

import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.io.OWLXMLOntologyFormat;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.model.OWLException;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;

import uk.ac.manchester.cs.util.SetUtils;

/**
 * A wrapper around a set of axioms. This class does not provide methods for
 * modifying the internal set of axioms and delegates equals and hashCode to it.
 * 
 * @author Pavel Klinov
 * 
 *         pklinov@cs.man.ac.uk, pklinov@clarkparsia.com
 * 
 *         Mar 6, 2011
 */
public class AxiomSet implements Iterable<OWLAxiom> {

	private Set<OWLAxiom> m_axioms = new HashSet<OWLAxiom>();
	private Set<OWLAxiom> m_nlAxioms = new HashSet<OWLAxiom>();
	private Set<OWLEntity> m_sig = null;

	public AxiomSet(Set<OWLAxiom> axioms) {
		if (axioms != null) {
			for (OWLAxiom axiom : axioms) {
				if (axiom.isLogicalAxiom()) {
					m_axioms.add(axiom);
				} else {
					m_nlAxioms.add(axiom);
				}
			}
		}

		updateSignature();
	}

	private void updateSignature() {
		m_sig = new HashSet<OWLEntity>(m_axioms.size() * 2);

		for (OWLAxiom axiom : m_axioms) {
			if (axiom.isLogicalAxiom()) {
				for (OWLEntity term : axiom.getSignature()) {
					m_sig.add(term);
				}
			}
		}
	}

	protected void addAxiom(OWLAxiom axiom) {
		if (axiom.isLogicalAxiom()) {
			m_axioms.add(axiom);
			m_sig.addAll(axiom.getSignature());
		} else {
			m_nlAxioms.add(axiom);
		}
	}

	public Set<OWLAxiom> getAxioms() {
		return m_axioms;
	}

	public Set<OWLAxiom> getAllAxioms() {
		return SetUtils.union(m_axioms, m_nlAxioms);
	}

	@Override
	public boolean equals(Object obj) {

		if (!(obj instanceof AxiomSet))
			return false;

		return m_axioms.equals(((AxiomSet) obj).getAxioms());
	}

	@Override
	public int hashCode() {

		return m_axioms.hashCode();
	}

	public Set<OWLEntity> getSignature() {

		return m_sig;
	}

	@Override
	public Iterator<OWLAxiom> iterator() {

		return m_axioms.iterator();
	}

	public void serializeInOWL(String fileName) throws OWLException {

		OWLOntologyManager mgr = OWLManager.createOWLOntologyManager();
		OWLOntology ontology = mgr.createOntology(m_axioms);
		File file = new File(fileName);

		mgr.saveOntology(ontology, new OWLXMLOntologyFormat(),
				IRI.create(file.toURI()));
	}

	@Override
	public String toString() {
		return m_axioms.toString();
	}
}